import React from "react";
import { Space, Table, Tag, message } from "antd";
import { ListApi } from "./request/api";
import { useEffect } from "react";
import { useState } from "react";
import { RemoveArticle } from "./request/api";
import { useNavigate } from "react-router-dom";

export default function List() {
  const navigate = useNavigate();
  const [listData, setListData] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 5,
    total: 0,
  });
  const [update, setUpdate] = useState(1);

  function getList(current, pageSize) {
    ListApi({ num: current, count: pageSize }).then((res) => {
      console.log(res);
      let data = res.data.arr.map((it) => {
        return Object.assign(it, (it.key = it.id));
      });
      setPagination({
        current: res.data.num,
        pageSize: res.data.count,
        total: res.data.total,
      });
      setListData(data);
    });
  }
  function removeList(e) {
    RemoveArticle({
      id: e.id,
    }).then((res) => {
      if (res.errCode == 0) {
        setUpdate(update + 1);
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    });
  }
  function editList(e) {
    navigate("/edit/" + e.id);
  }
  useEffect(() => {
    getList(pagination.current, pagination.pageSize);
  }, [update]);
  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "副标题",
      dataIndex: "subTitle",
      key: "subTitle",
    },
    {
      title: "时间",
      dataIndex: "date",
      key: "date",
    },

    {
      title: "操作",
      key: "action",
      render: (e) => (
        <Space size="middle">
          <a onClick={() => editList(e)}>编辑 </a>
          <a onClick={() => removeList(e)}>删除</a>
        </Space>
      ),
    },
  ];
  const data = listData;
  function Pagenation(e) {
    // setPagination(e);
    getList(e.current, e.pageSize);
  }

  return (
    <Table
      columns={columns}
      dataSource={data}
      pagination={pagination}
      onChange={(e) => Pagenation(e)}
    />
  );
}
